package com.zzx.boot.servlet.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzx.boot.constant.GlobalEnum;
import com.zzx.boot.entity.dto.AddCommentDto;
import com.zzx.boot.entity.table.Comment;
import com.zzx.boot.entity.table.Post;
import com.zzx.boot.entity.table.User;
import com.zzx.boot.entity.vo.CommentVo;
import com.zzx.boot.entity.vo.UserVo;
import com.zzx.boot.exception.SystemctlException;
import com.zzx.boot.mapper.CommentMapper;
import com.zzx.boot.servlet.CommentService;
import com.zzx.boot.servlet.PostService;
import com.zzx.boot.servlet.UserService;
import com.zzx.boot.utils.DateTImeUtils;
import com.zzx.boot.utils.SecurityUtils;
import com.zzx.boot.utils.Transaction;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author tan
 * @version 1.0
 * @date 2023/7/10 16:59
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {


    @Resource
    private PostService postService;
    @Resource
    private Transaction transaction;
    @Resource
    private UserService userService;

    @Override
    public String addComment(AddCommentDto commentDto) {
        // 获取用户
        User user = SecurityUtils.getLoginUser().getUser();
        // 判断文章是否存在
        Post post = postService.getById(commentDto.getPostId());
        if(Objects.isNull(post)){
            throw new SystemctlException(GlobalEnum.POST_EXISTS_ERROR);
        }
        Comment comment = new Comment(
                null,
                user.getId(),
                commentDto.getFid(),
                0L,
                commentDto.getData(),
                DateTImeUtils.getDate(),
                commentDto.getPostId());
        String success = transaction.submit(()->{
            // 判断是回复评论还是评论
            if(commentDto.getFid()>0){//回复
                if(!addCommentNum(commentDto.getFid())){
                    throw new SystemctlException(GlobalEnum.COMMENT_UPDATE_ERROR);
                }
            }
            int b = baseMapper.insert(comment);
            return (b==1&&commentDto.getFid()>0)?"回复评论成功":"添加评论成功";
        });

        return success;

    }

    @Override
    public List<CommentVo> getCommentPage(Long postId, Long current) {
        Page<Comment> page = new Page<>(current, 10);

        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getPostId,postId);
        wrapper.eq(Comment::getFid,0);// 获取一级评论
        Page<Comment> commentPage = baseMapper.selectPage(page, wrapper);
        List<Comment> list = baseMapper.selectList(new LambdaQueryWrapper<Comment>().eq(Comment::getPostId, postId).ne(Comment::getFid, 0));
        List<CommentVo> vos = commentPage.getRecords().stream().map(item -> {
            UserVo userVo = userService.getUserById(item.getUserId());
            List<CommentVo> children = getChildrenComment(list, item.getId());
            return new CommentVo(item.getId().toString(),
                    userVo, item.getFid(),
                    item.getFunm(),
                    item.getData(),
                    DateTImeUtils.getDate(), children);
        }).collect(Collectors.toList());
        return vos;


    }

    /**
     * 获取二级评论通过文章id
     * @return
     */
    private List<CommentVo> getChildrenComment(List<Comment> list,Long fid) {
        List<CommentVo> vos = list.stream().filter(item -> item.getFid().equals(fid)).map(item -> {

            UserVo userVo = userService.getUserById(item.getUserId());
            List<CommentVo> children = getChildrenComment(list, item.getId());
            return new CommentVo(item.getId().toString(),
                    userVo, item.getFid(),
                    item.getFunm(),
                    item.getData(),
                    DateTImeUtils.getDate(), children);
        }).collect(Collectors.toList());

        return vos;
    }



    /**
     * 评论数自增
     * @param id
     * @return
     */
    private boolean addCommentNum(Long id) {
        // 主评论自增
        Comment oldComment = baseMapper.selectById(id);
        oldComment.setFunm(oldComment.getFunm()+1);
        int i = baseMapper.updateById(oldComment);
        return i==1;
    }
}
